//
//  sdkDemoAppDelegate.m
//  sdkDemo
//
//  Created by qqconnect on 13-3-29.
//  Copyright (c) 2013年 qqconnect. All rights reserved.
//

#import "sdkDemoAppDelegate.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "SDKCall.h"

#if BUILD_QQAPIDEMO
#import "TencentOpenAPI/QQApiInterface.h"
#import "QQApiShareEntry.h"
#endif

#define OSVersion ([[[UIDevice currentDevice] systemVersion] floatValue])

static dispatch_queue_t logQueue;

@implementation sdkDemoAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"%s, %s", __FILE__, __FUNCTION__);
    //打开写日志到文件的开关
    [QQApiInterface setSwitchPrintLogToFile:YES];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        logQueue = dispatch_queue_create("com.qq.readinjoy.proteus.serialqueue", DISPATCH_QUEUE_SERIAL);
    });
    //打印日志的回调
    __weak __typeof(self) weakSelf = self;
    [QQApiInterface startLogWithBlock:^(NSString *logStr) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            // 用户没有授权同意隐私协议，导致SDK无法使用，所以在demo中增加弹窗提醒
            if (![logStr containsString:TCOpenSDKErrorMsgUserNotAgreedAuthorization]) {
                return;
            }
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"SDK日志信息"
                                                                message:TCOpenSDKErrorMsgUserNotAgreedAuthorization
                                                               delegate:nil
                                                      cancelButtonTitle:@"我知道了"
                                                      otherButtonTitles:nil];
            [alertView show];
        });
        dispatch_async(logQueue, ^{
            [strongSelf writeLogToFile:logStr];
        });
    }];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[sdkDemoViewController alloc] initWithStyle:UITableViewStyleGrouped];
    sdkDemoNavgationController *navController = [[sdkDemoNavgationController alloc] initWithRootViewController:self.viewController];
    [[self window] setRootViewController:navController];
    [[self window] makeKeyAndVisible];
    self.isRequestFromQQ = NO;
    
    [self performSelector:@selector(showChangeAppIDAlert) withObject:nil afterDelay:0];
    
    return YES;
}

- (void)writeLogToFile:(NSString *)log {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *logFilePath = [NSString stringWithFormat:@"%@/QQSDKDemo.log", docDir];
    
    // check the size of log file
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:logFilePath]) {
        [fileManager createFileAtPath:logFilePath contents:nil attributes:nil];
    }
    NSString *fileContent = [NSString stringWithContentsOfFile:logFilePath encoding:NSUTF8StringEncoding error:nil];
    fileContent = fileContent ?: @"";
    fileContent = [fileContent stringByAppendingFormat:@"\n%@", log];
    [fileContent writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
    self.isRequestFromQQ = NO;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"%s, %s, url = %@", __FILE__, __FUNCTION__, url);
#if (OPEN_SDK_UL_CI && OPEN_SDK_UL_DEBUG)
    static NSString *prefixUrl = @"https://qm.qq.com/qq_conn/102060558";
    static NSString *bundleId = @"com.tencent.opensdkdemo.db.vip";
    
    // testcase: mqqsignapp
    if (NSNotFound != [url.absoluteString rangeOfString:@"mqqsignapp"].location) {
        NSRange queryRange = [url.absoluteString rangeOfString:@"?"];
        NSString *queryStrEx = [url.absoluteString substringFromIndex:queryRange.location+1];
        NSString *universallink = nil;
        if (NSNotFound != [url.absoluteString rangeOfString:bundleId].location) {
            universallink = [NSString stringWithFormat:@"%s/%s/mqqsignapp?%s", [prefixUrl UTF8String], [bundleId UTF8String], [queryStrEx UTF8String]];
        }
        else {
            universallink = [NSString stringWithFormat:@"%s/mqqsignapp?%s", [prefixUrl UTF8String], [queryStrEx UTF8String]];
        }
        url = [NSURL URLWithString:universallink];
        [QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Where from" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertView show];
        return [TencentOAuth HandleUniversalLink:url];
    }
        
    // testcase: implfunction
    if (NSNotFound != [url.absoluteString rangeOfString:@"sdkactioninfo"].location) {
        // >=3.3.7 sdkactioninfo
        NSRange queryRange = [url.absoluteString rangeOfString:@"?"];
        NSString *queryStrEx = [url.absoluteString substringFromIndex:queryRange.location+1];
        NSString *universallink = [NSString stringWithFormat:@"%s/%s?%s", [prefixUrl UTF8String], [bundleId UTF8String], [queryStrEx UTF8String]];
        url = [NSURL URLWithString:universallink];
        [QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Where from" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertView show];
        return [TencentOAuth HandleUniversalLink:url];
    }
    else {
        // == 3.3.6
        NSRange schemeRange = [url.absoluteString rangeOfString:@"tencent102060558://"];
        NSString *schemePath = [url.absoluteString substringFromIndex:schemeRange.location+schemeRange.length];
        NSString *universallink = [NSString stringWithFormat:@"%s/tencent102060558/%s", [prefixUrl UTF8String], [schemePath UTF8String]];
        url = [NSURL URLWithString:universallink];
        [QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Where from" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertView show];
        return [TencentOAuth HandleUniversalLink:url];
    }
#endif
    
    [QQApiInterface handleOpenURL:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
    
    if (YES == [TencentOAuth CanHandleOpenURL:url])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CI Where from" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertView show];
        return [TencentOAuth HandleOpenURL:url];
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    NSLog(@"%s, %s, url = %@", __FILE__, __FUNCTION__, url);
    
    [QQApiInterface handleOpenURL:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
    
    if (YES == [TencentOAuth CanHandleOpenURL:url])
    {
        return [TencentOAuth HandleOpenURL:url];
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler NS_AVAILABLE_IOS(8_0);
{
    NSLog(@"%s, %s, url = %@", __FILE__, __FUNCTION__, userActivity.webpageURL);
    
    // Demo处理手Q UniversalLink回调的示例代码
    if([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        NSURL *url = userActivity.webpageURL;
        if(url && [TencentOAuth CanHandleUniversalLink:url]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CI UniversalLink" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alertView show];

            [QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
            return [TencentOAuth HandleUniversalLink:url];
        }
    }
    return YES;
}

#pragma mark -

- (void)showChangeAppIDAlert {
    NSString *appid = [[NSUserDefaults standardUserDefaults] objectForKey:TENCENT_APPID_USERDEFAULTS_KEY];
    if (appid.length > 0) {
        return;
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设置AppId" preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        NSString *appid = alert.textFields.firstObject.text;
        
        [[NSUserDefaults standardUserDefaults] setObject:appid forKey:TENCENT_APPID_USERDEFAULTS_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"新AppId重新启动应用后生效" preferredStyle:(UIAlertControllerStyleAlert)];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:nil]];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeAlways;
        textField.placeholder = @"输入AppId";
        textField.text = __TencentDemoAppid_;
    }];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}

- (void)setIsRequestFromQQ:(BOOL)isRequestFromQQ
{
    _isRequestFromQQ = isRequestFromQQ;
    UINavigationBar *navBar = self.viewController.navigationController.navigationBar;
    UIColor *newColor = nil;
    if (_isRequestFromQQ)
    {
        // 46,139,87
        newColor = [UIColor colorWithRed:(46/255.0) green:(139/255.0) blue:(87/255.0) alpha:1.0];
    }
    else
    {
        newColor = nil;
    }
    
    if (OSVersion >= 7.0)
    {
        navBar.barTintColor = newColor;
    }
    else
    {
        navBar.tintColor = newColor;
    }
}

@end
